package edu.biwu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 王俊彪
 * @version 1.0
 */
@Component
public class ConnectionFactory {

    @Autowired
    ThreadLocal<Connection> threadLocal;

    @Autowired
    DataSource dataSource;


    public Connection currentThreadConn(){
        //尝试从ThreadLocal中获取当前线程对应的连接
        Connection connection = threadLocal.get();
        //判断当前线程对应的是否有连接
        if (connection==null){
            try {
                //在连接池中获取一个线程
                connection = dataSource.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage());
            }
            //将连接与相当线程进行绑定
            threadLocal.set(connection);
        }
        return connection;
    }

}
